package learning.spring.contacts.service.jpa;

import com.google.common.collect.Lists;
import learning.spring.contacts.domain.Contact;
import learning.spring.contacts.repository.ContactRepository;
import learning.spring.contacts.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: bibro
 * Date: 21.02.14
 * Time: 21:04
 * To change this template use File | Settings | File Templates.
 */
//@Service("contactService")
@Repository
@Transactional
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactRepository contactRepository;

    @Override
    public List<Contact> findAll() {
        return (List<Contact>) contactRepository.findAll();
    }

    @Override
    public Contact findById(Long id) {
        return contactRepository.findOne(id);
    }

    @Override
    public Contact save(Contact contact) {
        contactRepository.save(contact);
        return contact;
    }

    @Override
    public Contact update(Contact contact) {
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public Iterable<Contact> findByFirstName(String firstName) {
        return contactRepository.findByFirstName(firstName);
    }

    @Override
    public Iterable<Contact> findByLastName(String lastName) {
        return contactRepository.findByLastName(lastName);
    }

    @Override
    public Iterable<Contact> findByFistNameAndLastName(String firstName, String lastName) {
        if (firstName == null && lastName == null) {
            return findAll();
        }
        else if (firstName == null)
            return findByLastName(lastName);
        else if (lastName == null)
            return findByFirstName(firstName);

        return contactRepository.findByFirstNameAndLastName(firstName, lastName);
    }
}
